const connection = require('./db')

// 执行sql语句
const query = (sql) => {
    return new Promise((resolve, reject)=> {
        connection.query(sql, (err, data) => {
            if(err) reject(err)
            resolve(data)
        })
    })
}

// 查
const getData = async (tablename, condition = '') => {
    const mycondition = condition ? ` where ${condition}` : ''
    const result = await query(`select * from ${tablename} ${mycondition}`)
    return result
}

// 增
const insertData = async (tablename, data = {}) => {
    let mydata = ''
    let dot = ''
    for(const key in data) {
        mydata += `${dot}${key}='${data[key]}'`
        dot = ','
    }
    const result = await query(`insert into ${tablename} set ${mydata}`)
    return result
}

module.exports = {
    getData,
    insertData
}